package com.ptms.config;

import com.ptms.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException; // 修正1：去掉多余的.Servlet
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j; // 修正2：用@Slf4j注解替代手动定义Logger（Lombok标准用法）
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; // 修正3：去掉多余的.security
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter; // 修正4：去掉多余的.filter

import java.io.IOException;

/**
 * 适配角色权限的JWT过滤器：负责Token提取、验证、用户权限加载、上下文注入
 */
@Component
@Slf4j // Lombok注解：自动生成log对象（无需手动new Logger）
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    // 依赖：构造器注入（保持原有逻辑）
    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserDetailsService userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException { // 此处已修正ServletException包路径

        try {
            // 1. 提取Token（保持原有逻辑）
            String authHeader = request.getHeader("Authorization");
            String token = null;
            String username = null;

            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
                username = jwtUtil.getUsernameFromToken(token);
                log.debug("从Token解析到用户名：{}", username);
            }

            // 2. 注入认证上下文（保持原有逻辑）
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                if (jwtUtil.validateToken(token)) {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities()
                    );
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                    log.info("JWT验证通过，用户[{}]角色：{}", username, userDetails.getAuthorities());
                }
            }
        } catch (Exception e) {
            // 异常处理（保持原有逻辑）
            SecurityContextHolder.clearContext();
            String errorMsg = "JWT验证失败：";
            if (e.getMessage().contains("user not found")) errorMsg += "用户不存在";
            else if (e.getMessage().contains("expired")) errorMsg += "Token已过期";
            else if (e.getMessage().contains("signature")) errorMsg += "Token签名无效";
            else errorMsg += e.getMessage();

            log.error(errorMsg, e); // 用Lombok自动生成的log对象
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"" + errorMsg + "\",\"data\":null}");
            return;
        }

        filterChain.doFilter(request, response);
    }
}
